namespace DataDesign.MPP.AddIn
{
    using System;
    using Extensibility;
    using System.Runtime.InteropServices;
    using System.Reflection;

    using System.Windows.Forms;

    using MSProject = Microsoft.Office.Interop.MSProject;
    using DataDesign.MPP.Utilities;
    using DataDesign.MPP.ServerManager;


	#region Read me for Add-in installation and setup information.
	// When run, the Add-in wizard prepared the registry for the Add-in.
	// At a later time, if the Add-in becomes unavailable for reasons such as:
	//   1) You moved this project to a computer other than which is was originally created on.
	//   2) You chose 'Yes' when presented with a message asking if you wish to remove the Add-in.
	//   3) Registry corruption.
	// you will need to re-register the Add-in by building the DataDesignAddInSetup project, 
	// right click the project in the Solution Explorer, then choose install.
	#endregion
	
	/// <summary>
	///   The object for implementing an Add-in.
	/// </summary>
	/// <seealso class='IDTExtensibility2' />
	[GuidAttribute("69D0E80E-C5F3-43E4-9BFB-F79094F3B488"), ProgId("DataDesignAddIn.Connect")]
	public class Connect : Object, Extensibility.IDTExtensibility2
	{
		/// <summary>
		///		Implements the constructor for the Add-in object.
		///		Place your initialization code within this method.
		/// </summary>
        private static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        MSProject.Application msApp = null;
        MSProject.Project msProject = null;
        private void InitLog4net()
        {
            //string _configFile = System.Reflection.Assembly.GetExecutingAssembly().Location + ".config";
            string _configFile = Common.GetConfigFilePath();
            System.IO.FileInfo fInfo = new System.IO.FileInfo(_configFile);
            log4net.Config.XmlConfigurator.Configure(fInfo);

            // reconfigure the RollingFileAppender for this assembly
            // We will look for the appender whose name matches with the file name (e.g. MyProject.MyAdmin.dll) of this assembly
            string appenderName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            appenderName = System.IO.Path.GetFileName(appenderName);

            log4net.Appender.IAppender[] appenders = logger.Logger.Repository.GetAppenders();
            foreach (log4net.Appender.IAppender appender in appenders)
            {
                if (appender.Name.Equals(appenderName))
                {
                    log4net.Appender.RollingFileAppender fileAppender = appender as log4net.Appender.RollingFileAppender;
                    fileAppender.File = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(_configFile), "MPP.AddIn.log");
                    fileAppender.ActivateOptions();

                    break;
                }
            }
        }
        public Connect()
        {
            try
            {
                InitLog4net();
                logger.Debug("Init log4net sucess !");
            }
            catch (Exception ex)
            {
                DataDesign.MPP.AddIn.HelperAddIn.ShowError("Config log4net FAIL !. Exception: " + ex.Message);
            }
        }

        /// <summary>
        ///      Implements the OnConnection method of the IDTExtensibility2 interface.
        ///      Receives notification that the Add-in is being loaded.
        /// </summary>
        /// <param term='application'>
        ///      Root object of the host application.
        /// </param>
        /// <param term='connectMode'>
        ///      Describes how the Add-in is being loaded.
        /// </param>
        /// <param term='addInInst'>
        ///      Object representing this Add-in.
        /// </param>
        /// <seealso class='IDTExtensibility2' />
        public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
        {
            applicationObject = application;
            addInInstance = addInInst;
        }

        /// <summary>
        ///     Implements the OnDisconnection method of the IDTExtensibility2 interface.
        ///     Receives notification that the Add-in is being unloaded.
        /// </summary>
        /// <param term='disconnectMode'>
        ///      Describes how the Add-in is being unloaded.
        /// </param>
        /// <param term='custom'>
        ///      Array of parameters that are host application specific.
        /// </param>
        /// <seealso class='IDTExtensibility2' />
        public void OnDisconnection(Extensibility.ext_DisconnectMode disconnectMode, ref System.Array custom)
        {
        }

        /// <summary>
        ///      Implements the OnAddInsUpdate method of the IDTExtensibility2 interface.
        ///      Receives notification that the collection of Add-ins has changed.
        /// </summary>
        /// <param term='custom'>
        ///      Array of parameters that are host application specific.
        /// </param>
        /// <seealso class='IDTExtensibility2' />
        public void OnAddInsUpdate(ref System.Array custom)
        {
        }

        /// <summary>
        ///      Implements the OnStartupComplete method of the IDTExtensibility2 interface.
        ///      Receives notification that the host application has completed loading.
        /// </summary>
        /// <param term='custom'>
        ///      Array of parameters that are host application specific.
        /// </param>
        /// <seealso class='IDTExtensibility2' />
        public void OnStartupComplete(ref System.Array custom)
        {
            try
            {
                // Test deploy, if success, show success message
                //HelperAddIn.ShowInfo("Success!!!");

                //Init();
                msApp = (MSProject.Application)applicationObject;

                ButtonMenu button = new ButtonMenu(msApp, addInInstance);
                button.AddButton();

                msApp.FileCloseEx(MSProject.PjSaveType.pjDoNotSave, Missing.Value, Missing.Value);
                logger.Debug("Hook event of Application");
                msApp.ProjectBeforeClose2 += new MSProject._EProjectApp2_ProjectBeforeClose2EventHandler(msApp_ProjectBeforeClose2);

                logger.Debug("BEGIN HelperServerManager.Load");
                HelperServerManager.Load();
                logger.Debug("END HelperServerManager.Load");
            }
            catch (Exception ex)
            {
                logger.Error("ERROR OnStartupComplete", ex);
                HelperAddIn.ShowError(ex);
            }
        }
        void msApp_ProjectBeforeClose2(MSProject.Project pj, MSProject.EventInfo Info)
        {
            HelperAddIn.ShowInfo("Hook before close !");
        }
        /// <summary>
        ///      Implements the OnBeginShutdown method of the IDTExtensibility2 interface.
        ///      Receives notification that the host application is being unloaded.
        /// </summary>
        /// <param term='custom'>
        ///      Array of parameters that are host application specific.
        /// </param>
        /// <seealso class='IDTExtensibility2' />
        public void OnBeginShutdown(ref System.Array custom)
        {
        }

        private object applicationObject;
        private object addInInstance;
	}
}